/*
 * ============================================================================
 *
 *       Filename:  user.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  03/16/19 16:34:27
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  jianxi sun (jianxi), ycsunjane@gmail.com
 *   Organization:  
 *
 * ============================================================================
 */
#include <stdio.h>
#include <stdint.h>

#include "common.h"
#include "user.h"
#include "buffer2.h"

LIST_HEAD(urluser_head);
urluser_t *urluser_arr;

int maxid = 0;
static int invalid_id(int id)
{
	if(id >= maxid || id < 0) {
		fprintf(stderr, "id: %d invalid\n", id);
		return 1;
	}
	return 0;
}

void url_show(buffer2_t *buf)
{
	int ret;
	char buffer[BUF_SIZE];
	struct urluser *pos;

	breset(buf);
	list_for_each_entry(pos, &urluser_head, node) {
		ret = snprintf(buffer, BUF_SIZE, "url: %s, id: %d\n",
			pos->url, pos->id);
		bconcat(buf, buffer, ret);
	}

	return;
}

int url_add(char *url)
{
	int ret = 0;
	struct urluser *pos, *newurl;

	/* lock */
	list_for_each_entry(pos, &urluser_head, node) {
		if(strcmp(pos->url, url) == 0) {
			fprintf(stderr, "url %s must diffrent within %d length\n", 
				url, URL_MAXLEN);
			ret = -1;
			goto end;
		}
	}

	newurl = malloc(sizeof(urluser_t));
	strncpy(newurl->url, url, URL_MAXLEN - 1);
	newurl->id = maxid++;
	list_add_tail(&(newurl->node), &urluser_head);

end:
	/* unlock */
	return ret;
}

void urluser_clean(struct urluser *pos)
{
	list_del(&(pos->node));
	free(pos);
}

int url_del(char *idstr)
{
	int id = strtol(idstr, NULL, 10);
	if(invalid_id(id))
		return -1;

	int ret = -1;
	struct urluser *pos, *n;
	list_for_each_entry_safe(pos, n, &urluser_head, node) {
		if(pos->id == id) {
			urluser_clean(pos);
			ret = 0;
		}
	}
	return ret;
}
